package com.topView2;

import com.algorithm.graphtheory.adj.AdjMatrix;
import com.bean.TreeNode;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author: huangzhigao
 * @Date: 2023/2/12 19:44
 */
public class leecode105 {
    private Map<Integer, Integer> map = new HashMap<>();

    public TreeNode buildTree(int[] preorder, int[] inorder) {
        for (int i = 0; i < inorder.length; i++) {
            map.put(inorder[i], i);
        }
        return build(preorder, 0, preorder.length - 1, inorder, 0, inorder.length - 1);
    }

    public TreeNode build(int[] preorder, int preStart, int preEnd, int[] inOrder, int inStart, int inEnd) {
        if (preStart > preEnd) {
            return null;
        }

        int head = preorder[preStart];
        TreeNode treeNode = new TreeNode(head);
        //获取中点位置
        int index = map.get(head);
        int leftSize = index - inStart;
        treeNode.left = build(preorder, preStart + 1, preStart + leftSize, inOrder, inStart, index - 1);
        treeNode.right = build(preorder, preStart + leftSize + 1, preEnd, inOrder, index + 1, inEnd);
        return treeNode;
    }
}
